package com.hxl.tech.gateway.auth.context;

import cn.hutool.core.util.StrUtil;
import com.hxl.tech.gateway.auth.dto.UserInfo;
import com.hxl.tech.gateway.common.constant.AppConstant;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;


public class ContextHolder {

    private static final ThreadLocal<Map<String, Object>> sessionHolder = new InheritableThreadLocal<>();

    private static final String USER_INFO = "userInfo";

    public static UserInfo getUserInfo() {

        return (UserInfo) getOrCreate().get(USER_INFO);
    }

    public static void setUserInfo(UserInfo userInfo) {

        getOrCreate().put(USER_INFO, userInfo);
    }

    private static Map<String, Object> getOrCreate() {
        Map<String, Object> map = sessionHolder.get();
        if (map == null) {
            synchronized (Thread.currentThread()) {
                map = sessionHolder.get();
                if (map == null) {
                    map = new ConcurrentHashMap<>();
                    sessionHolder.set(map);
                }
            }
        }
        return map;
    }

    public static Boolean isDeveloper() {
        return StrUtil.equals(AppConstant.ROLE_DEVELOPER, getUserInfo().getRoleName());
    }

    public static Boolean isAdmin() {
        return StrUtil.equals(AppConstant.ROLE_ADMIN, getUserInfo().getRoleName());
    }

    public static void clear() {
        sessionHolder.remove();
    }
}
